package com.trg.designmodel.prototype.copy;

import java.io.*;

/**
 * @ClassName: Schoole
 * @Description:    深拷贝案例
 * @Author: tangrg
 * @Date: 2021/7/2 10:47
 * @Version: 1.0
 * @Return:
 **/
public class Schoole implements Cloneable, Serializable {
    private static final long serialVersionUID = 2L;

    private String name;
    private String loc;
    private Student student;

    public Schoole(String name, String loc) {
        this.name = name;
        this.loc = loc;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLoc() {
        return loc;
    }

    public void setLoc(String loc) {
        this.loc = loc;
    }

    public Student getStudent() {
        return student;
    }

    public void setStudent(Student student) {
        this.student = student;
    }

    @Override
    public String toString() {
        return "Schoole{" +
                "name='" + name + '\'' +
                ", loc='" + loc + '\'' +
                ", student=" + student +
                '}';
    }

    /**
     * 深拷贝方式一、实现Clone方法
     * Clone()方法，只能拷贝基本类型和String字符
     * @return
     * @throws CloneNotSupportedException
     */
    @Override
    protected Object clone() throws CloneNotSupportedException {
        //1、先通过Schoole类中的super.clone();将Schoole中的基本类型和字符先进行拷贝
        Schoole schoole = (Schoole)super.clone();
        //2、对Schoole中的引用类型再进行拷贝
        schoole.student = (Student) student.clone();
        return schoole;
    }

    /**
     * 深拷贝方式二：通过序列化的方式实现
     * 设计思想：
     * 先对该对象序列化， 然后再进行反序列化
     * @return
     */
    public Schoole deepCopy(){
        ByteArrayOutputStream bos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;
        ObjectOutputStream oos = null;
        try{
            //先将对象进行序列化
             bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);
            //然后将对象进行反序列化
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            Schoole schoole = (Schoole) ois.readObject() ;
            return schoole;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
